package com.ruoyi.common.utils.aliyun;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.ruoyi.common.utils.VerifyCodeUtils;

public class SendMessage {
    static final String PRODUCT = "Dysmsapi";
    static final String DOMAIN = "dysmsapi.aliyuncs.com";
    static final String ACCESSKEYID = "LTAIvMvTxaIlwGgH";
    static final String ACCESSKEYSECRET = "ItmAYXGR5Yqt5eNxzqEQKtOd5C6MDk";
    static final String TEMPLATECODE = "SMS_129755890";

    public static boolean sendSms(String phoneNumber,Integer code) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESSKEYID, ACCESSKEYSECRET);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", PRODUCT, DOMAIN);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phoneNumber);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("安比科技");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(TEMPLATECODE);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        // 判断是否发送成功
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            //请求成功
            System.out.println("返回的状态码：" + sendSmsResponse.getCode());
            System.out.println("返回的信息：" + sendSmsResponse.getMessage());
            return true;
        } else {
            //isv.BUSINESS_LIMIT_CONTROL：
            //业务限流：将短信发送频率限制在正常的业务流控范围内，默认流控：短信验证码 ：使用同一个签名，对同一个手机号码发送短信验证码，支持1条/分钟，5条/小时 ，累计10条/天。
            System.out.println("信息发送失败！");
        }
        return false;
    }

    public static void main(String[] args) throws Exception {
        sendSms("18078565630", VerifyCodeUtils.getCaptcha());

    }
}
